package dfbz.com.controller.login;

import com.alibaba.fastjson.JSON;
import dfbz.com.constant.Const;
import dfbz.com.controller.BaseServlet;
import dfbz.com.model.User;
import dfbz.com.service.UserInfoService;
import dfbz.com.service.UserService;
import dfbz.com.service.impl.UserInfoServiceImpl;
import dfbz.com.service.impl.UserServiceImpl;
import dfbz.com.utils.MailUtil;
import dfbz.com.utils.StrUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@WebServlet("/user/*")
public class LoginServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    private UserInfoService userInfoService=new UserInfoServiceImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        session.setAttribute("userdeptname",userService.finddept(username));

        if (null != username && null != password) {
            //企业项目的规范，控制层里面尽可能不要写业务逻辑代码
            boolean existUser = userService.findUserByNameAndPwd(username, password);
            String msg;
            if (!existUser) {
                msg = "error";//表示去 渲染登录失败的页面
                resp.sendRedirect("/index.jsp");
            } else {
                msg = "info";//info表示 登录成功 渲染学生信息管理系统页面
                //登录成功之后，给session设置属性
//                HttpSession session = req.getSession();
                session.setAttribute("userInfo", username);
                //常量的数值，不要随随便便写进我们的业务代码，这种称魔法值
                session.setMaxInactiveInterval(Const.MAX_SESSION_TIME);
//                resp.sendRedirect("/html/home.jsp");
                req.getRequestDispatcher("/html/home.jsp").forward(req, resp);

            }
//            req.getSession().setAttribute("msg", msg);

        }

    }
//    public void userlist(HttpServletRequest req, HttpServletResponse resp){
//        req.setAttribute("userinfoList", userInfoService.findUserInfo());
//        try {
//            req.getRequestDispatcher("/html/user.jsp").forward(req, resp);
//        } catch (ServletException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


    public void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        resp.setHeader("Content-type", "application/json");
        User user;
        if (null != username) {
            user = userService.findUserBaseInfo(username);
            if (null != user) {
                String jsonString = JSON.toJSONString(user);
                resp.getWriter().write(jsonString);
            } else {
                resp.getWriter().write("{}");
            }
        } else {
            resp.getWriter().write("{}");
        }
    }

    public static boolean isEmail(String email) {
        // 1、\\w+表示@之前至少要输入一个匹配字母或数字或下划线 \\w 单词字符：[a-zA-Z_0-9]
        // 2、(\\w+\\.)表示域名. 如新浪邮箱域名是sina.com.cn
        // {1,3}表示可以出现一次或两次或者三次.
        String reg = "\\w+@(\\w+\\.){1,3}\\w+";
        Pattern pattern = Pattern.compile(reg);
        boolean flag = false;
        if (email != null) {
            Matcher matcher = pattern.matcher(email);
            flag = matcher.matches();
        }
        return flag;
    }
/*
用户邮件发送
 */
    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-Type", "text/html");
        resp.setCharacterEncoding("UTF-8");

        String useremail = req.getParameter("email");
        User uEmail = userService.findUserEmail(useremail);
        String title = "邮箱已经发送过去，请注意查收！";
        String code = StrUtil.randomCode();
        String Content = "你的验证码是：" + code;
        HttpSession session = req.getSession();
        if (isEmail(useremail)) {

            if (uEmail != null) {
                //一开始先判断session里面有没有code
                Object obj = session.getAttribute(useremail);
                if (null == obj) {
                    //把code放进session里
                    session.setAttribute(useremail, code);
                    session.setMaxInactiveInterval(Const.MAX_CODE_TIME);
                    try {
                        MailUtil.send(useremail, title, Content, MailUtil.UNICODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            } else {
                req.setAttribute("msg", "该邮箱不是用户邮箱");
                req.getRequestDispatcher("/forget.jsp").forward(req, resp);
            }

        } else {
            req.setAttribute("msg", "该邮箱格式不正确");
            req.getRequestDispatcher("/forget.jsp").forward(req, resp);
        }


    }
    /*
    重置密码
     */
    public void register(HttpServletRequest req, HttpServletResponse resp){
        String useremail = req.getParameter("useremail");
        String newpassword = req.getParameter("newpassword");
        String emailcode = req.getParameter("emailcode");
        HttpSession session = req.getSession();
        Object obj = session.getAttribute(useremail);
        if (null!=obj){
            String code = obj.toString();
            if(code.equals(emailcode)){
                User user = userService.findUserEmail(useremail);
                if(user!=null){
                    userService.restnewpsw(user.getId(),newpassword);
                    try {
                        req.getRequestDispatcher("/index.jsp").forward(req, resp);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;

                }
            }


        }




    }
    
    
    

/*
用户注册
 */
    
    public void add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");
        User user;

        //req.setCharacterEncoding("UTF-8");
        Map<String, String[]> map = req.getParameterMap();
        if (null != username) {
            user = userService.findUserBaseInfo(username);
            User userEmail = userService.findUserEmail(email);
            if (password.equals(password2)) {
                if (null == user) {
                    if (null == userEmail) {
                        if (isEmail(email)) {
                            try {
                                user = new User();
                                BeanUtils.populate(user, map);
                                userService.add(user);
                                System.out.println();
                                resp.sendRedirect("/index.jsp");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            req.setAttribute("msg", "该邮箱格式出错");
                            req.getRequestDispatcher("/register.jsp").forward(req, resp);
                        }
                    } else {
                        req.setAttribute("msg", "该邮箱已经存在");
                        req.getRequestDispatcher("/register.jsp").forward(req, resp);
                    }

                } else {
                    req.setAttribute("msg", "该用户名已经存在");
                    req.getRequestDispatcher("/register.jsp").forward(req, resp);
                }

            } else {
                req.setAttribute("msg", "密码前后不匹配");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
            }


        }
    }
    /***
     * 显示列表
     */
}
